package com.waymap.Thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public  class TheadsFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group ;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    TheadsFactory() {
        //默认namePrefix = default-name-pool
        this("default-name-pool");
    }

    TheadsFactory(String name){
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        this.namePrefix = name +
                poolNumber.getAndIncrement();
    }

    @Override
    public Thread newThread(Runnable r) {
        //此时线程的名字 就是 namePrefix + -thread- + 这个线程池中第几个执行的线程
        Thread t = new Thread(group, r,
                namePrefix + "-thread-"+threadNumber.getAndIncrement(),
                0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }

}
